//
//  HWOpenVipController.swift
//  HWanGame
//
//  Created by 王昌健 on 2021/12/7.
//  Copyright © 2021 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView
import Alamofire
class HWOpenVipController: HWBaseViewController {
    var topBgView:UIView!
    var topImageView:UIImageView!
    var topOpenButton:UIButton!
    var bottomBgView:UIView!
    
    var userInfoView:HWVipUserInfoView!
    
    var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect.zero)
    var segmentedDataSource: JXSegmentedTitleDataSource!
    
    var contentScrollView:UIScrollView!
    
    var contentBgView:UIView!
    
    var tipsLabel:UILabel!
    
    var openButton:UIButton!
    
    ///存放功能名称
    var titles:[UILabel] = Array()
    ///存放功能按钮
    var buttons:[UIButton] = Array()
    ///存放功能图
    var images:[UIImageView] = Array()
    ///存放功能锁
    var lockViews:[HWOpenVipLockView] = Array()
    var httpManager = HWVIPHttpManager()
    var vipLevelArr:[String] = Array()
    var infoModel = HWVIPHomeInfoModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        loadData()
        
        addAction()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        UIColor.gradientColor(view: topBgView, colors: [UIColor.colorWithHexString(hexString: "#646468").cgColor,
                                                        UIColor.colorWithHexString(hexString: "#33333F").cgColor,],start: CGPoint(x: 0, y: 0),end: CGPoint(x: 1, y: 1))
        
        bottomBgView.addCorner(conrners: [.topLeft,.topRight], radius: 29)
        
        UIColor.gradientColor(view: openButton, colors: [UIColor.colorWithHexString(hexString: "#454651").cgColor,
                                                         UIColor.colorWithHexString(hexString: "#41414A").cgColor,],start: CGPoint(x: 0, y: 0),end: CGPoint(x: 1, y: 1))
    }
    
}

extension HWOpenVipController {
    private func initUI() -> Void {
        navigationView.backgroundColor = .clear
        navigationView.titleLabel.text = "游享会员"
        navigationView.titleLabel.textColor = .white
        
        topBgView = UIView()
        view.addSubview(topBgView)
        view.sendSubviewToBack(topBgView)
        
        topImageView = UIImageView()
        topImageView.image = UIImage(named: "openVIP")
        topImageView.isUserInteractionEnabled = true
        view.addSubview(topImageView)
        
        topOpenButton = UIButton(type: .custom)
        topOpenButton.setImage(UIImage(named: "openButtonImage"), for: .normal)
        topOpenButton.addTarget(self, action: #selector(openButtonClick(_:)), for: .touchUpInside)
        topImageView.addSubview(topOpenButton)
        
        userInfoView = HWVipUserInfoView()
        view.addSubview(userInfoView)
        
        topImageView.isHidden = true
        userInfoView.isHidden = true
        
        bottomBgView = UIView()
        bottomBgView.backgroundColor = .colorWithHexString(hexString: "#F3F4F8")
        view.addSubview(bottomBgView)
        
        segmentedDataSource = JXSegmentedTitleDataSource()
        segmentedDataSource.titles = [""]
        
        segmentedDataSource.isTitleColorGradientEnabled = true
        segmentedDataSource.titleNormalColor = UIColor.colorWithHexString(hexString: "#999999")
        segmentedDataSource.titleSelectedColor = UIColor.colorWithHexString(hexString: "#333333")
        segmentedDataSource.titleNormalFont = UIFont.init(name: "YouSheBiaoTiHei", size: 14*widthScale)!
        segmentedDataSource.titleSelectedFont = UIFont.init(name: "YouSheBiaoTiHei", size: 16*widthScale)!
        
        segmentedView.dataSource = segmentedDataSource
        
        let indicator = JXSegmentedIndicatorImageView()
        indicator.image = UIImage(named: "indicator")
        indicator.indicatorHeight = 7*widthScale
        indicator.indicatorWidth = 21*widthScale
        segmentedView.indicators = [indicator]
        segmentedView.delegate = self
        segmentedView.backgroundColor = .colorWithHexString(hexString: "#F3F4F8")
        bottomBgView.addSubview(self.segmentedView)
        
        contentScrollView = UIScrollView()
        contentScrollView.backgroundColor = .clear
        contentScrollView.showsVerticalScrollIndicator = false
        bottomBgView.addSubview(contentScrollView)
        
        contentBgView = UIView()
        contentBgView.backgroundColor = .white
        contentBgView.layer.cornerRadius = 16
        contentScrollView.addSubview(contentBgView)
        
        tipsLabel = HWLabel.createLabel(title: "", color: "#999999", font: 10*widthScale)
        contentScrollView.addSubview(tipsLabel)
        
        openButton = UIButton(type: .custom)
        openButton.setTitle("开通VIP", for: .normal)
        openButton.titleLabel?.font = .boldSystemFont(ofSize: 18*widthScale)
        openButton.setTitleColor(.colorWithHexString(hexString: "#C29B5B"), for: .normal)
        openButton.backgroundColor = .colorWithHexString(hexString: "#454651")
        openButton.layer.cornerRadius = 6 * widthScale
        openButton.layer.masksToBounds = true
        openButton.addTarget(self, action: #selector(openButtonClick(_:)), for: .touchUpInside)
        contentBgView.addSubview(openButton)
        
    }
    
    private func initFrame() -> Void {
        topBgView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(screenHeight/2)
        }
        
        topImageView.snp.makeConstraints { make in
            make.left.equalTo(10*widthScale)
            make.right.equalTo(-10*widthScale)
            make.top.equalTo(navigationView.snp.bottom).offset(7*widthScale)
            make.height.equalTo(topImageView.snp.width).multipliedBy(0.44)
        }
        
        topOpenButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-26 * widthScale)
        }
        
        userInfoView.snp.makeConstraints { make in
            make.left.equalTo(15*widthScale)
            make.right.equalTo(-15*widthScale)
            make.top.equalTo(navigationView.snp.bottom).offset(7*widthScale)
            make.height.equalTo(topImageView.snp.width).multipliedBy(0.44)
        }
        
        bottomBgView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(topImageView.snp.bottom).offset(20*widthScale)
        }
        
        segmentedView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(15*widthScale)
            make.height.equalTo(30*widthScale)
        }
        
        contentScrollView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(segmentedView.snp.bottom).offset(10*widthScale)
        }
        
        contentBgView.snp.makeConstraints { make in
            make.left.equalTo(15*widthScale)
            make.width.equalTo((screenWidth - 30*widthScale))
            //            make.height.equalTo(365 * widthScale)
            make.top.equalTo(0)
        }
        
        tipsLabel.snp.makeConstraints { make in
            make.left.equalTo(23*widthScale)
            make.width.equalTo(screenWidth - 46*widthScale)
            make.top.equalTo(contentBgView.snp.bottom).offset(10*widthScale)
        }
        
        openButton.snp.makeConstraints { make in
            make.left.equalTo(26*widthScale)
            make.right.equalTo(-26*widthScale)
            make.bottom.equalTo(-7 * widthScale)
            make.height.equalTo(38 * widthScale)
        }
    }
}

extension HWOpenVipController {
    func loadData() -> Void {
        httpManager.getVIPHomeInfo { model in
            
//            if model.top.vip == 0 {
//                self.userInfoView.isHidden = false
//            }
            
            self.infoModel = model
            self.createItems(models: model.gongneng)
            self.vipLevelArr.removeAll()
            for mod in model.dengji{
                self.vipLevelArr.append(mod.title)
            }
            self.segmentedDataSource.titles = self.vipLevelArr
            self.segmentedView.reloadData()
            self.segmentedView.selectItemAt(index: model.top.vip)
            
            ///未开通vip显示开通按钮
            if model.top.vip == 0 {
                self.topImageView.sd_setImage(with: URL(string: model.top.bgimg))
                self.topOpenButton.isHidden = false
                self.topImageView.isHidden = false
                self.openButton.setTitle("开通VIP", for: .normal)
            }else {
                self.topOpenButton.isHidden = true
                self.userInfoView.isHidden = false
                self.userInfoView.model = model.top
                self.openButton.setTitle("续费VIP", for: .normal)
            }
            self.tipsLabel.text = model.jieshao
            
            var str = model.jieshao.removingPercentEncoding
            
            str = self.base64Decoding(encodedString: str ?? "")
            let srtData = str?.data(using: String.Encoding.unicode, allowLossyConversion: true)!
            
            let attrStr = try! NSMutableAttributedString(data: srtData!, options: [.documentType: NSAttributedString.DocumentType.html,.characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
            attrStr.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 10*widthScale), range: NSRange(location: 0, length: attrStr.length))
            
            self.tipsLabel.attributedText = attrStr
            
            
            self.contentBgView.layoutIfNeeded()
            self.contentScrollView.contentSize = CGSize(width: 0, height: self.contentBgView.frame.size.height + self.heightOfAttributedString(attrStr) + 40)
            
        } failure: { error in
            
        }
        
    }
    /// 获取attributeString高度
    func heightOfAttributedString(_ attributedString: NSAttributedString) -> CGFloat {
        let height = attributedString.boundingRect(with: CGSize(width: UIScreen.main.bounds.size.width - 23 * 2, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).height
        return ceil(height)
    }
    
    /// base64解码
    func base64Decoding(encodedString:String)->String
    
    {
        let decodedData = NSData(base64Encoded: encodedString, options: NSData.Base64DecodingOptions.init(rawValue: 0))
        
        let decodedString = NSString(data: decodedData! as Data, encoding: String.Encoding.utf8.rawValue)! as String
        
        return decodedString
        
    }
    
}

extension HWOpenVipController {
    func createItems(models:[HWVIPHomeGoneNengModel]) -> Void {
        
        for v in titles {
            v.removeFromSuperview()
        }
        
        for v in buttons {
            v.removeFromSuperview()
        }
        
        for v in images {
            v.removeFromSuperview()
        }
        
        for v in lockViews {
            v.removeFromSuperview()
        }
        
        titles.removeAll()
        buttons.removeAll()
        images.removeAll()
        lockViews.removeAll()
        
        if self.titles.count>0 {
            for i in 0..<models.count {
                self.titles[i].text = models[i].title
                if models[i].status == true {
                    self.images[i].sd_setImage(with: URL(string: models[i].icon), completed: nil)
                    self.titles[i].textColor = .colorWithHexString(hexString: "#999999")
                }else {
                    self.images[i].sd_setImage(with: URL(string: models[i].icon_no), completed: nil)
                    self.titles[i].textColor = .colorWithHexString(hexString: "#333333")
                }
            }
        }else{
            var tempView:UIView!
            for i in 0..<models.count {
                let imageBgView = UIView()
                imageBgView.backgroundColor = .colorWithHexString(hexString: "#F3F4F8")
                imageBgView.layer.cornerRadius = 22 * widthScale
                contentBgView.addSubview(imageBgView)
                let imageView = UIImageView()
                imageView.backgroundColor = .colorWithHexString(hexString: "#F3F4F8")
                imageView.layer.cornerRadius = 22 * widthScale
                imageBgView.addSubview(imageView)
                
                //功能名称
                let label = HWLabel.createLabel(title: "-", color: "#333333", font: 10)
                contentBgView.addSubview(label)
                
                //锁头
                let lockView = HWOpenVipLockView()
                contentBgView.addSubview(lockView)
                
                //功能点击按钮
                let button = UIButton(type: .custom)
                button.backgroundColor = .clear
                button.tag = models[i].type
                button.addTarget(self, action: #selector(buttonClick(_:)), for: .touchUpInside)
                contentBgView.addSubview(button)
                
                if tempView != nil {
                    if i % 3 == 0 {
                        imageBgView.snp.makeConstraints { make in
                            make.left.equalTo(22 * widthScale)
                            make.top.equalTo(tempView.snp.bottom).offset(30)
                            make.width.height.equalTo(tempView)
                        }
                        
                    }else {
                        imageBgView.snp.makeConstraints { make in
                            make.left.equalTo(tempView.snp.right).offset(49 * widthScale)
                            make.top.equalTo(tempView)
                            make.width.height.equalTo(tempView)
                        }
                    }
                    
                }else {
                    imageBgView.snp.makeConstraints { make in
                        make.left.equalTo(22 * widthScale)
                        make.width.equalTo(68 * widthScale)
                        make.height.equalTo(68 * widthScale)
                        make.top.equalTo(20)
                    }
                    
                }
                
                tempView = imageBgView
                
                imageView.snp.makeConstraints { make in
                    make.center.equalToSuperview()
                    make.width.height.equalTo(36 * widthScale)
                }
                
                label.snp.makeConstraints { make in
                    make.top.equalTo(imageBgView.snp.bottom).offset(5)
                    make.centerX.equalTo(imageBgView)
                }
                
                if i == models.count - 1 {
                    openButton.snp.makeConstraints { make in
                        make.top.equalTo(label.snp.bottom).offset(22)
                    }
                }
                lockView.snp.makeConstraints { make in
                    make.top.equalTo(imageBgView)
                    make.left.equalTo(imageBgView.snp.left).offset(-4)
                }
                
                button.snp.makeConstraints { make in
                    make.left.right.top.equalTo(imageBgView)
                    make.bottom.equalTo(label)
                }
                
                label.text = models[i].title
                if models[i].status == true {
                    imageView.sd_setImage(with: URL(string: models[i].icon), completed: nil)
                    label.textColor = .colorWithHexString(hexString: "#999999")
                }else {
                    imageView.sd_setImage(with: URL(string: models[i].icon_no), completed: nil)
                    label.textColor = .colorWithHexString(hexString: "#333333")
                }
                
                images.append(imageView)
                titles.append(label)
                buttons.append(button)
                lockViews.append(lockView)
            }
        }
        
        
        for i in 0..<(self.infoModel.gongneng.count) {
            if self.infoModel.gongneng[i].tiaojian <= self.infoModel.dengji[0].tiaojian{
                self.images[i].sd_setImage(with: URL(string: self.infoModel.gongneng[i].icon), completed: nil)
                self.lockViews[i].isHidden = true
                self.titles[i].textColor = .colorWithHexString(hexString: "#333333")
                
            }else {
                self.images[i].sd_setImage(with: URL(string: self.infoModel.gongneng[i].icon_no), completed: nil)
                self.lockViews[i].isHidden = false
                self.lockViews[i].titleLabel.text = self.infoModel.gongneng[i].tiaojian_name
                self.titles[i].textColor = .colorWithHexString(hexString: "#999999")
            }
        }
    }
}

extension HWOpenVipController:JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
 
        for i in 0..<(self.infoModel.gongneng.count) {
            if self.infoModel.gongneng[i].tiaojian <= self.infoModel.dengji[index].tiaojian{
                self.images[i].sd_setImage(with: URL(string: self.infoModel.gongneng[i].icon), completed: nil)
                self.lockViews[i].isHidden = true
                self.titles[i].textColor = .colorWithHexString(hexString: "#333333")
            }else {
                self.images[i].sd_setImage(with: URL(string: self.infoModel.gongneng[i].icon_no), completed: nil)
                self.lockViews[i].isHidden = false
                self.lockViews[i].titleLabel.text = self.infoModel.gongneng[i].tiaojian_name
                self.titles[i].textColor = .colorWithHexString(hexString: "#999999")
            }
//            self.lockViews[i].isHidden = true
        }
    }
}

extension HWOpenVipController {
    @objc func buttonClick(_ button:UIButton) -> Void {
        print("buttonTag=====\(button.tag)")
        
        self.httpManager.getVIPAlertInfo(typeId: button.tag) { model in
            let alert = HWOpenVipFunctionAlert()
            alert.model = model
            alert.show()
            
            alert.jumpToVipCenter = {
                let centerController = HWVipCenterController()
                centerController.callBack = {
                    self.loadData()
                }
                self.navigationController?.pushViewController(centerController, animated: true)
            }
        } failure: { error in
            
        }
        
    }
}

extension HWOpenVipController {
    func addAction() -> Void {
        userInfoView.openButtonClick = {
            self.jumpToPay()
        }
    }
    
    @objc func openButtonClick(_ :UIButton) -> Void {
        self.jumpToPay()
    }
    
    func jumpToPay() -> Void {
//        let webController = HWWebController()
//        webController.urlString = self.infoModel.top.pay_url
        //按照安卓修改为
        self.navigationController?.pushViewController(HWVIPController(), animated: true)
    }
}
